package com.hjx.security;

import com.hjx.entity.SysUser;
import com.hjx.mapper.LoginAndAuthMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>Title:加载用户权限</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/10 - 9:07
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Resource
    LoginAndAuthMapper loginAndAuthMapper;
    @Override
    public UserDetails loadUserByUsername(String uno) throws UsernameNotFoundException {
        //根据用户编号查询用户信息
        SysUser user = loginAndAuthMapper.findUserById(uno);
        //根据用户编号查询用户的角色
        List<String> roleCodes = loginAndAuthMapper.findRoleByUserId(uno);
        //根据用户的角色查询角色所拥有的权限
        List<String> auth = loginAndAuthMapper.findAuthByRoleCode(roleCodes);
        //将角色添加到权限的集合中
        auth.addAll(roleCodes);
        List<GrantedAuthority> grantedAuthorities =
                AuthorityUtils.createAuthorityList(auth.toArray(new String[0]));
        //返回一个User对象
        return new User(user.getUno(),user.getPassword(),grantedAuthorities);
    }
}
